package com.coscon;


import it.sauronsoftware.junique.AlreadyLockedException;
import it.sauronsoftware.junique.JUnique;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import java.awt.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;


/**
 * 入口
 * @author 409390047@qq.com
 * @Date: 2021/6/16 10:13
 */
@SpringBootApplication
@ServletComponentScan
@EnableScheduling
@Slf4j
public class RunApplication extends SpringBootServletInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
        SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
        sessionCookieConfig.setHttpOnly(true);
    }

    private static void initMacDockImage(){
        try {
            Class appClass = Class.forName("com.apple.eawt.Application");
            Class params[] = new Class[]{Image.class};
            Method getApplication = appClass.getMethod("getApplication");
            Object application = getApplication.invoke(appClass);
            Method setDockIconImage = appClass.getMethod("setDockIconImage", params);
            setDockIconImage.invoke(application, ImageIO.read(RunApplication.class.getResource("/static/macDockImage.png")));
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | ClassNotFoundException | IOException ex) {
            ex.printStackTrace();
        }
    }


	public static void main(String[] args) {

        //根据main函数名锁定实例为一个
        String id = RunApplication.class.getName();
        boolean start;
        try {
            JUnique.acquireLock(id, null);
            start = true;
        } catch (AlreadyLockedException e) {
            start = false;
            log.warn(e.getMessage());
        }
        if (start) {
            if(SystemUtils.IS_OS_MAC){//如果是mac系统，初始化dock的图标
                initMacDockImage();
            }
            SpringApplicationBuilder builder = new SpringApplicationBuilder(RunApplication.class);
            builder.headless(false).run(args);
        }

    }
}
